package org.noote.libs.widget;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

public class WidgetSquare2D {

	private FloatBuffer vertexBuffer;
	private FloatBuffer texCoordsBuffer;
	
	private float[] vertices = {
			-1.0f, -1.0f, 0.0f,
			-1.0f, 1.0f, 0.0f,
			1.0f, -1.0f, 0.0f,			
			1.0f, 1.0f, 0.0f
	};
	float[] texCoords = {
			0.0f, 0.0f,
			0.0f, 1.0f,
			1.0f, 0.0f,	
			1.0f, 1.0f
	};
	protected float color[] = {1, 1, 1, 1};

	int textureID = 0;

	public WidgetSquare2D(int texID) {
		textureID = texID;
		
		_updateVertexBuffer();
		_updateTexCoordsBuffer();
	}
	
	public void setSize(float fX, float fY, float fZ)
	{
		float[] vertices = 
		{
			0.0f, fY, fZ,
			0.0f, 0.0f, fZ,
			fX, fY, fZ,			
			fX, 0.0f, fZ
		};
		setVertices(vertices);
	}
	public void setTextureID(int textureID)
	{
		this.textureID = textureID;
	}
	public void setColor(float c[])
	{
		this.color = c;
	}

	public float[] getVertices() {
		return vertices;
	}

	public void setVertices(float[] vertices) {
		this.vertices = vertices;
		_updateVertexBuffer();
	}

	protected void _allocVertexBuffer() {
		if (vertexBuffer == null) {
			ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
			vbb.order(ByteOrder.nativeOrder());
			vertexBuffer = vbb.asFloatBuffer();
		}
	}

	protected void _allocTexCoordsBuffer() {
		if (texCoordsBuffer == null) {
			ByteBuffer vbb = ByteBuffer.allocateDirect(texCoords.length * 4);
			vbb.order(ByteOrder.nativeOrder());
			texCoordsBuffer = vbb.asFloatBuffer();
		}
	}

	protected void _updateVertexBuffer() {
		if (vertexBuffer == null)
			_allocVertexBuffer();
		vertexBuffer.position(0);
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);
	}

	protected void _updateTexCoordsBuffer() {
		if (texCoordsBuffer == null)
			_allocTexCoordsBuffer();
		texCoordsBuffer.position(0);
		texCoordsBuffer.put(texCoords);
		texCoordsBuffer.position(0);
	}

	// Render the shape
	public void draw(GL10 gl) {
		
		gl.glFrontFace(GL10.GL_CCW);
		gl.glDisable(GL10.GL_CULL_FACE);
		
		gl.glColor4f(color[0], color[1], color[2], color[3]);
		 
		gl.glEnable(GL10.GL_TEXTURE_2D);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);
		gl.glEnable( GL10.GL_BLEND );
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
		gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, texCoordsBuffer);

		gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glDisable( GL10.GL_BLEND );
		gl.glDisable(GL10.GL_TEXTURE_2D);
	}
}
